<template>
  <div class="h-full min-h-0 overflow-hidden flex flex-col gap-18px text-white relative">
    <!-- 返回按钮 - 固定在右上角 -->
    <div class="absolute right-0 top--2 z-10 text-[#fff] cursor-pointer" @click="returnIndexPage">
      <img src="@/assets/bi_images/return.png" alt="返回" class="w-[60px] h-[55px]" />
    </div>

    <!-- 上方：风险指标运行统计 -->
    <DsPanel class="!h-[30%] min-h-0" title="风险指标运行统计">
      <div ref="wrapperRef" class="relative overflow-hidden border border-[rgba(60,190,255,0.28)] rounded-[12px] py-3 h-[calc(100%-30px)] min-h-0">
        <div ref="trackRef" class="flex gap-1 transition-transform duration-250 ease-out will-change-transform h-full min-h-0" :style="trackStyle">
          <BizCard
            v-for="card in bizBlocks"
            :key="card.title"
            class="h-full min-h-0 shrink-0 w-[260px] overflow-hidden"
            :title="card.title"
            :icon="card.icon"
            :headers="card.headers"
            :rows="periodRows"
            :sample-fn="sampleCell"
          />
        </div>
      </div>
      <!-- 滚动条 -->
      <div ref="scrollbarRef" class="relative mt-2.5 h-[17px] bg-[#1B3F74]">
        <div
          class="absolute top-0 h-[13px] cursor-pointer transition-[box-shadow] duration-200 bg-[linear-gradient(90deg,rgba(165,220,255,0),#57A6FF)] border border-[#4FB8FF] hover:shadow-[0_0_10px_rgba(45,205,255,0.65)]"
          :style="thumbStyle"
          @mousedown="handleThumbMouseDown"
        />
      </div>
    </DsPanel>

    <!-- 下方：风险状态监测 + 风险要素计算 -->
    <div class="grid grid-cols-[40fr_60fr] gap-18px !h-[70%] min-h-0">
      <DsPanel class="" title="风险状态监测">
        <div class="relative h-full">
          <VChart class="absolute inset-0" :option="radarOption" autoresize @click="handleRadarClick" />
          <!-- 右上角：当前安全指数 -->
          <div
            class="absolute right-10px top-10px w-[173px] h-[45px] bg-[url(/src/assets/bi_images/shuju.png)] bg-no-repeat bg-center bg-[length:100%_100%] flex flex-col items-center justify-center text-center"
          >
            <div class="text-[10px] text-[#cfe6ff] pb-[10px]">当前安全指数</div>
            <div class="text-[25px] font-800 text-[#60c9ff] leading-[1.1] pb-[10px]">{{ currentScore.toFixed(1) }}</div>
          </div>
        </div>
      </DsPanel>

      <DsPanel title="风险要素计算">
        <div class="h-full grid grid-cols-[20fr_80fr] gap-18px">
          <div class="rounded-[12px] px-3 py-4 flex flex-col items-center justify-center text-center">
            <div
              class="text-[15px] w-[80px] text-[rgba(207,230,255,0.85)] bg-[url(@/assets/bi_images/defen.png)] bg-no-repeat bg-center bg-[length:100%_auto] min-h-[24px] px-[10px] py-[4px] text-left"
            >
              得分
            </div>
            <div class="text-[22px] font-800 text-[#4BBEFA] text-left">{{ currentScore.toFixed(1) }}</div>
            <img class="w-[120px] h-auto object-contain" src="@/assets/bi_images/group_15.png" alt="score" />
            <div
              class="text-[15px] w-[80px] text-[rgba(207,230,255,0.85)] bg-[url(@/assets/bi_images/defen.png)] bg-no-repeat bg-center bg-[length:100%_auto] min-h-[24px] px-[10px] py-[4px] mt-[6px] text-left"
            >
              总分
            </div>
            <div class="text-[22px] font-800 text-[#4BBEFA] text-left">{{ totalScore.toFixed(1) }}</div>
          </div>

          <div class="h-full min-h-0 flex flex-col">
            <div class="mb-3">
              <img class="h-[32px] object-contain" src="@/assets/bi_images/biaoti.png" alt="标题" />
            </div>
            <el-table
              ref="tableRef"
              :data="tableRows"
              height="100%"
              stripe
              :span-method="spanMethod"
              :row-class-name="getRowClass"
              :cell-class-name="getCellClass"
            >
              <el-table-column prop="index" label="序号" width="70" />
              <el-table-column prop="category" label="风险要素大类" class-name="category-col" />
              <el-table-column prop="subCategory" label="风险要素小类" />
              <el-table-column prop="decision" label="否决项" />
              <el-table-column prop="reason" label="说明原因" />
              <el-table-column prop="penalty" label="扣分" align="center" />
            </el-table>
          </div>
        </div>
      </DsPanel>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch, nextTick } from 'vue';

// 定义组件属性
const props = defineProps<{
  selectedCategory?: string;
}>();

// 定义事件
const emits = defineEmits<{
  (e: 'hideDrill'): void;
}>();
import DsPanel from '../DsPanel.vue';
import BizCard from './components/BizCard.vue';
import VChart from 'vue-echarts';
import type { ECBasicOption } from 'echarts/types/dist/shared';
import { getRiskIndexStatistics } from '@/api/ds';

import iconYufang from '@/assets/bi_images/yufang.png';
import iconHuilu from '@/assets/bi_images/huilu.png';
import iconKekaoxing from '@/assets/bi_images/kekaoxing.png';
import iconGongyi from '@/assets/bi_images/gongy8i.png';
import iconSis from '@/assets/bi_images/sis.png';
import iconGsd from '@/assets/bi_images/gsd.png';
import iconTeshu from '@/assets/bi_images/teshu.png';
import iconRenyuan from '@/assets/bi_images/renyuan.png';

interface RiskRow {
  index: number;
  category: string;
  subCategory: string;
  decision: string;
  reason: string;
  penalty: number;
}

const avgIndex = ref(63);
const totalScore = ref(0);
const statisticsData = ref<any>(null);

// 动态得分：根据选中的要素大类显示对应分值
const currentScore = computed(() => {
  if (!statisticsData.value) return 0;

  // 如果有选中的要素大类，显示该大类的得分
  if (effectiveSelectedCategory.value && effectiveSelectedCategory.value !== '') {
    const categoryData = statisticsData.value[effectiveSelectedCategory.value];
    if (categoryData && typeof categoryData === 'object' && 'score' in categoryData) {
      return parseFloat(categoryData.score) || 0;
    }
  }

  // 否则显示当前安全指数
  return parseFloat(statisticsData.value.indexScore) || 0;
});

// 本页内的本地选中（优先级高于外部传入的 props.selectedCategory）
// null 表示尚未本地交互，沿用父级初始高亮；
// '' 表示用户主动清空高亮；
// 其它字符串表示用户本地选择的分类。
const localSelectedCategory = ref<string | null>(null);
const effectiveSelectedCategory = computed(() => (localSelectedCategory.value !== null ? localSelectedCategory.value : props.selectedCategory || ''));

// 风险要素大类名称映射
const categoryNameMap: Record<string, string> = {
  doublePrevention: '双重预防',
  controlCircuit: '控制回路',
  sisSide: 'SIS联锁旁路',
  processAlarm: '工艺报警',
  deviceRun: '设备可靠性',
  personAggregation: '人员聚集',
  gdsAlarm: 'GDS报警',
  specialWork: '特殊作业'
};

const bizBlocks = [
  {
    icon: iconYufang,
    title: '双重预防',
    headers: ['隐患总数', '重大隐患', '未整改']
  },
  {
    icon: iconHuilu,
    title: '控制回路',
    headers: ['有效自控率']
  },
  {
    icon: iconKekaoxing,
    title: '设备可靠性',
    headers: ['检修完成率', '报警总数', '一级报警']
  },
  {
    icon: iconGongyi,
    title: '工艺报警',
    headers: ['操作平稳率', '报警总数', 'A类报警']
  },
  {
    icon: iconSis,
    title: 'SIS连锁旁路',
    headers: ['旁路数量']
  },
  {
    icon: iconGsd,
    title: 'GDS报警',
    headers: ['总数', '可燃', '有毒']
  },
  {
    icon: iconTeshu,
    title: '特殊作业',
    headers: ['总数', '动火', '受限', '高处', '吊装']
  },
  {
    icon: iconRenyuan,
    title: '人员聚集',
    headers: ['红色报警', '橙色报警', '黄色报警']
  }
] as const;

const periodRows = ['近7天', '近30天', '当年'] as const;

function sampleCell(blockTitle: string, header: string, row: string) {
  const seed = (blockTitle + header + row).length;
  if (/%$/.test(header) || /率$/.test(header)) {
    const v = 60 + (seed % 40);
    return v + '%';
  }
  return (seed % 120).toString();
}

// 计算表格数据
const tableRows = computed<RiskRow[]>(() => {
  if (!statisticsData.value) return [];

  const rows: RiskRow[] = [];
  let index = 1;

  // 用户在本页点击雷达后才进行过滤；
  // 初始从父组件带入的高亮不触发表格过滤。
  const selectedForFilter = localSelectedCategory.value !== null && localSelectedCategory.value !== '' ? localSelectedCategory.value : '';

  // 遍历所有风险要素大类
  Object.entries(statisticsData.value).forEach(([key, categoryData]) => {
    // 跳过非风险要素字段
    if (key === 'indexScore' || key === 'totalScore') return;

    // 若存在本地选中分类，则只保留该分类的数据
    if (selectedForFilter && key !== selectedForFilter) return;

    const categoryName = categoryNameMap[key] || key;

    // 遍历该大类下的所有子项
    categoryData.riskSubItemVos?.forEach((subItem) => {
      rows.push({
        index: index++,
        category: categoryName,
        subCategory: subItem.subTypeName,
        decision: subItem.isNegated === 1 ? '是' : '否',
        reason: subItem.deductionReason || '',
        penalty: parseFloat(subItem.deductionScore) || 0
      });
    });
  });

  return rows;
});

// 表格合并单元格函数
const spanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (columnIndex === 1) {
    // 风险要素大类列
    const currentCategory = row.category;
    let rowspan = 1;
    const colspan = 1;

    // 查找相同类别的连续行数
    for (let i = rowIndex + 1; i < tableRows.value.length; i++) {
      if (tableRows.value[i].category === currentCategory) {
        rowspan++;
      } else {
        break;
      }
    }

    // 检查是否是该类别的第一行
    if (rowIndex === 0 || tableRows.value[rowIndex - 1].category !== currentCategory) {
      return { rowspan, colspan };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }
  return { rowspan: 1, colspan: 1 };
};

// 表格行样式函数
const getRowClass = ({ row }: any) => {
  if (effectiveSelectedCategory.value && categoryNameMap[effectiveSelectedCategory.value] === row.category) {
    return 'highlighted-row';
  }
  return '';
};

// 表格单元格样式函数：确保合并后的“大类”单元格整体高亮
const getCellClass = ({ row, column }: any) => {
  if (column?.property === 'category') {
    if (effectiveSelectedCategory.value && categoryNameMap[effectiveSelectedCategory.value] === row.category) {
      return 'highlighted-category-cell';
    }
  }
  return '';
};

// 获取风险指数统计数据
const fetchRiskIndexStatistics = async () => {
  try {
    const response = await getRiskIndexStatistics();
    statisticsData.value = response.data;

    // 更新总分
    if (statisticsData.value) {
      totalScore.value = 100;
    }
  } catch (error) {
    console.error('获取风险指数统计数据失败:', error);
  }
};

const radarOption = computed<ECBasicOption>(() => {
  // 根据接口数据生成雷达图数值
  const radarData: number[] = [];
  const radarIndicators: Array<{ name: string; max: number }> = [];

  // 数据映射
  const dataMapping = [
    { key: 'doublePrevention', title: '双重预防' },
    { key: 'controlCircuit', title: '控制回路' },
    { key: 'deviceRun', title: '设备可靠性' },
    { key: 'processAlarm', title: '工艺报警' },
    { key: 'sisSide', title: 'SIS连锁旁路' },
    { key: 'gdsAlarm', title: 'GDS报警' },
    { key: 'specialWork', title: '特殊作业' },
    { key: 'personAggregation', title: '人员聚集' }
  ];

  if (statisticsData.value) {
    dataMapping.forEach((item) => {
      const categoryData = statisticsData.value![item.key];
      const score = categoryData && typeof categoryData === 'object' && 'score' in categoryData ? parseFloat(categoryData.score) || 0 : 0;
      radarData.push(score);

      // 根据选中状态设置指标样式，在label中换行显示数值
      const isSelected = effectiveSelectedCategory.value === item.key;

      // 使用不同的name格式来强制ECharts重新渲染
      radarIndicators.push({
        name: isSelected ? `[*]${item.title}\n${score.toFixed(1)}` : `${item.title}\n${score.toFixed(1)}`,
        max: 100,
        axisLabel: {
          show: false
        }
      } as any);
    });
  } else {
    // 默认数据
    dataMapping.forEach((item) => {
      radarData.push(0);
      radarIndicators.push({
        name: `${item.title}\n0.0`,
        max: 100,
        axisLabel: {
          show: false
        }
      } as any);
    });
  }

  return {
    tooltip: {
      show: false
    },
    radar: {
      triggerEvent: true,
      radius: '60%',
      splitNumber: 4,
      indicator: radarIndicators,
      axisName: {
        formatter: (value: string, indicator: any) => {
          // 从name中提取标题判断是否选中
          let firstLine = value.split('\n')[0];
          const isSelected = firstLine.startsWith('[*]');

          // 移除选中标记
          if (isSelected) {
            firstLine = firstLine.substring(3);
          }

          // 使用富文本格式实现换行和高亮
          const lines = value.split('\n');
          const secondLine = lines[1] || '';

          // 根据选中状态使用不同的富文本样式
          if (isSelected) {
            return `{selected|${firstLine}}\n{selectedValue|${secondLine}}`;
          } else {
            return `{normal|${firstLine}}\n{normalValue|${secondLine}}`;
          }
        },
        rich: {
          // 正常状态的标题
          normal: {
            color: 'rgba(255,255,255,0.8)',
            fontSize: 12,
            fontWeight: 'normal',
            lineHeight: 16
          },
          // 正常状态的数值
          normalValue: {
            color: 'rgba(255,255,255,0.8)',
            fontSize: 12,
            fontWeight: 'normal',
            lineHeight: 16
          },
          // 选中状态的标题
          selected: {
            color: '#28d9ff',
            fontSize: 14,
            fontWeight: 'bold',
            lineHeight: 18
          },
          // 选中状态的数值
          selectedValue: {
            color: '#28d9ff',
            fontSize: 12,
            fontWeight: 'bold',
            lineHeight: 16
          }
        }
      },
      axisLine: { lineStyle: { color: 'rgba(79,161,255,0.3)' } },
      splitLine: { lineStyle: { color: 'rgba(79,161,255,0.2)' } },
      splitArea: {
        areaStyle: {
          color: ['rgba(32, 67, 124, 0.35)', 'rgba(32, 67, 124, 0.15)']
        }
      },
      // 禁用雷达坐标系本身触发tooltip
      axisPointer: {
        show: false
      }
    },
    series: [
      {
        type: 'radar',
        symbol: 'circle',
        symbolSize: (params: any) => {
          // 如果有选中的分类，高亮对应的点
          if (effectiveSelectedCategory.value && statisticsData.value) {
            const selectedIndex = dataMapping.findIndex((item) => item.key === effectiveSelectedCategory.value);
            return params.dataIndex === selectedIndex ? 10 : 6;
          }
          return 6;
        },
        lineStyle: { color: '#3cdfff', width: 2 },
        itemStyle: {
          color: (params: any) => {
            // 如果有选中的分类，高亮对应的点
            if (effectiveSelectedCategory.value && statisticsData.value) {
              const selectedIndex = dataMapping.findIndex((item) => item.key === effectiveSelectedCategory.value);
              return params.dataIndex === selectedIndex ? '#28d9ff' : '#fff';
            }
            return '#fff';
          },
          borderColor: '#3cdfff',
          borderWidth: 2
        },
        emphasis: {
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 3,
            shadowBlur: 10,
            shadowColor: '#3cdfff'
          }
        },
        areaStyle: { color: 'rgba(60, 223, 255, 0.25)' },
        data: [
          {
            value: radarData
          }
        ]
      }
    ]
  };
});

const trackRef = ref<HTMLDivElement | null>(null);
const wrapperRef = ref<HTMLDivElement | null>(null);
const scrollbarRef = ref<HTMLDivElement | null>(null);

// 0..1
const scrollPercent = ref(0);
const isDragging = ref(false);
const startX = ref(0);
const startPercent = ref(0);

// measured sizes
const viewportWidth = ref(0);
const contentWidth = ref(0);
const barWidth = ref(0);

const extraWidth = computed(() => Math.max(contentWidth.value - viewportWidth.value, 0));
const thumbWidth = computed(() => {
  // 无可滚动内容时，滑块占满，禁用拖动
  if (extraWidth.value <= 0) return barWidth.value;
  // 固定滑块宽度 80px（不超过滚动条宽度）
  return Math.min(80, barWidth.value);
});
const thumbMaxX = computed(() => Math.max(barWidth.value - thumbWidth.value, 0));

const trackStyle = computed(() => ({
  transform: `translateX(-${scrollPercent.value * extraWidth.value}px)`
}));

const thumbStyle = computed(() => ({
  width: `${thumbWidth.value}px`,
  transform: `translateX(${scrollPercent.value * thumbMaxX.value}px)`
}));

function updateSizes() {
  viewportWidth.value = wrapperRef.value?.clientWidth ?? 0;
  contentWidth.value = trackRef.value?.scrollWidth ?? 0;
  barWidth.value = scrollbarRef.value?.clientWidth ?? 0;
  // keep percent in range in case sizes changed
  if (thumbMaxX.value === 0) {
    scrollPercent.value = 0;
  } else {
    scrollPercent.value = Math.min(Math.max(scrollPercent.value, 0), 1);
  }
}

function handleThumbMouseDown(event: MouseEvent) {
  isDragging.value = true;
  startX.value = event.clientX;
  startPercent.value = scrollPercent.value;
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
}

function handleMouseMove(event: MouseEvent) {
  if (!isDragging.value) return;
  const delta = event.clientX - startX.value;
  scrollPercent.value = thumbMaxX.value === 0 ? 0 : Math.min(Math.max(startPercent.value + delta / thumbMaxX.value, 0), 1);
}

function handleMouseUp() {
  isDragging.value = false;
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
}

const returnIndexPage = () => {
  emits('hideDrill');
};

// 表格引用与自动滚动到高亮行
const tableRef = ref<any>(null);
async function scrollToHighlighted() {
  await nextTick();
  try {
    const tableEl = (tableRef.value?.$el ?? null) as HTMLElement | null;
    const body = tableEl?.querySelector('.el-table__body-wrapper') as HTMLElement | null;
    const target = body?.querySelector('tbody tr.highlighted-row') as HTMLElement | null;
    if (body && target) {
      const top = Math.max(target.offsetTop - 20, 0);
      if (typeof tableRef.value?.setScrollTop === 'function') {
        tableRef.value.setScrollTop(top);
      } else {
        body.scrollTop = top;
      }
    }
  } catch (e) {
    // ignore
  }
}

onMounted(() => {
  updateSizes();
  window.addEventListener('resize', updateSizes);
  fetchRiskIndexStatistics();
  scrollToHighlighted();
});

onBeforeUnmount(() => {
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  window.removeEventListener('resize', updateSizes);
});

// 当选中大类或表格数据变化时，自动滚动到高亮行
watch([() => props.selectedCategory, tableRows], () => {
  scrollToHighlighted();
});

// 雷达点击：切换高亮分类；重复点击同一分类则清空高亮并恢复表格
function handleRadarClick(params: any) {
  console.log('Radar click params:', params);

  const titleToKey: Record<string, string> = {
    双重预防: 'doublePrevention',
    控制回路: 'controlCircuit',
    设备可靠性: 'deviceRun',
    工艺报警: 'processAlarm',
    SIS连锁旁路: 'sisSide',
    GDS报警: 'gdsAlarm',
    特殊作业: 'specialWork',
    人员聚集: 'personAggregation'
  };

  let key: string | undefined;

  // 点击雷达图的label（axisName）
  if (params?.componentType === 'radar' && params?.name) {
    // 从富文本格式化后的name中提取标题
    const fullName = params.name;

    // 处理富文本格式：{selected|标题} 或 {normal|标题}
    let title = '';
    const richTextMatch = fullName.match(/\{(?:selected|normal)\|([^}]+)\}/);
    if (richTextMatch) {
      title = richTextMatch[1];
    } else {
      // 如果不是富文本格式，直接提取第一行
      title = fullName.split('\n')[0];
      // 移除可能的选中标记
      if (title.startsWith('[*]')) {
        title = title.substring(3);
      }
    }

    key = titleToKey[title];
  }
  // 点击雷达系列（series）
  else if (params?.componentType === 'series' && params?.seriesType === 'radar') {
    // 点击的是雷达图区域，也触发选中
    return;
  }

  if (!key) {
    console.log('Key not found for title');
    return;
  }

  console.log('Current effectiveSelectedCategory:', effectiveSelectedCategory.value);
  console.log('Clicked key:', key);

  // 首次交互后，后续不再回落到父级初始高亮
  if (effectiveSelectedCategory.value === key) {
    // 再次点击同一个分类，清空高亮（设置为 '' 表示用户主动清空）
    console.log('Clearing selection');
    localSelectedCategory.value = '';
  } else {
    // 选中新的分类
    console.log('Setting selection to:', key);
    localSelectedCategory.value = key;
  }
}

// 选中变化也滚动一次
watch(effectiveSelectedCategory, () => {
  scrollToHighlighted();
});
</script>

<style scoped>
:deep(.panel-body) {
  /* 确保每个面板的内容区域不因内部内容撑高，交由内部滚动 */
  overflow: hidden;
}
/* 行内所有列文字常驻高亮（颜色） */
:deep(.highlighted-row),
:deep(.highlighted-row .el-table__cell),
:deep(.highlighted-row .el-table__cell .cell) {
  color: #28d9ff !important;
  font-weight: 600;
}

/* 合并后的“大类”单元格仅文字常驻高亮（无背景） */
:deep(td.highlighted-category-cell),
:deep(td.highlighted-category-cell .cell) {
  color: #28d9ff !important;
  font-weight: 700;
}

/* （字体适配在 BizCard 组件内处理） */
</style>
